package com.hydra.auth.utils;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;


@Slf4j
public class AESUtil {

    private static final Integer DEFAULT_BYTE_LENGTH = 16;

    private static final String DEFAULT_SECRET_VALUE = "AES";

    /**
     * 加密内容
     * @param content 加密内容
     * @param strKey 加密 密钥
     * @param ivKey 初始化内容 (16位)
     * @return 返回加密后内容
     * @throws Exception    异常
     */
    public static String encrypt(String content,String strKey, String ivKey) throws Exception {
        SecretKeySpec sKeySpec = getKey(strKey);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(ivKey.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, sKeySpec, iv);
        byte[] encrypted = cipher.doFinal(content.getBytes());
        return  bytesToString(encrypted);
    }

    /**
     * 解密内容
     * @param content 加密内容
     * @param strKey 解密 密钥
     * @param ivKey 初始化内容 (16位)
     * @return 解密后内容
     * @throws Exception    异常
     */
    public static String decrypt(String content,String strKey, String ivKey) throws Exception {
        SecretKeySpec sKeySpec = getKey(strKey);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(ivKey.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, sKeySpec, iv);
        byte[] original = cipher.doFinal(stringToBytes(content));
        return new String(original);
    }

    /**
     * 返回加密对象
     * @param strKey 加密对象
     * @return key
     */
    private static SecretKeySpec getKey(String strKey) {
        byte[] arrBTmp = strKey.getBytes();
        byte[] arrB = new byte[DEFAULT_BYTE_LENGTH]; // 创建一个空的16位字节数组（默认值为0）
        for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
            arrB[i] = arrBTmp[i];
        }
        return new SecretKeySpec(arrB, DEFAULT_SECRET_VALUE);
    }

    /**
     * 字节数组转化为字符串
     */
    private static String bytesToString(byte[] content) {
        return Base64.getEncoder().encodeToString(content);
    }

    /**
     * 字符串转为字节数组
     */
    private static byte[] stringToBytes(String content) {
        return Base64.getDecoder().decode(content);
    }


    public static void main(String[] args) throws Exception {
        String aesKey = "0123456789abcdef";
        String aesIv = "abcdef0123456789";

        String data = "{\"uuid\":\"966e0a12-b4eb-4fa2-ade3-407212443413\"}";
        log.info("加密前参数：{}", data);

        String encrypt = AESUtil.encrypt(data, aesKey, aesIv);
        log.info("加密后结果：{}", encrypt);

        String decrypt = AESUtil.decrypt(encrypt, aesKey, aesIv);
        log.info("解密后结果：{}", decrypt);
    }

}
